<?php

/**
 * ScratchCard form.
 *
 * @package    Amman to London
 * @subpackage form
 * @author     Adel Abu-Saif <adeljas@msn.com>
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class ScratchCardForm extends BaseScratchCardForm {

    private $numbers = '0123456789';

    public function configure() {
        unset($this['created_at']);
        unset($this['card_number']);

        $this->widgetSchema['number_of_cards'] = new sfWidgetFormInput();

        $this->widgetSchema->setHelps(array('value' => 'JOD'));
        $this->validatorSchema->setOption('allow_extra_fields', true);
        $this->validatorSchema->setOption('filter_extra_fields', false);
    }

    public function save($con = null) {
        ini_set('max_execution_time', 0);
        $number_of_cards = $this->getValue('number_of_cards');
        $value = $this->getValue('value');
        for ($i = 1; $i <= $number_of_cards; $i++) {
            $card_number = $this->get_random_string($this->numbers, 14);
            // check if this number is already used 
            $res = ScratchCardTable::getInstance()->getByCardNumber($card_number);
            while ($res !== false) {
                $card_number = $this->get_random_string($this->numbers, 14);
                $res = ScratchCardTable::getInstance()->getByCardNumber($card_number);
            }
            $obj = new ScratchCard();
            $obj->set('value', $value);
            $obj->set('created_at', date('Y-m-d H:i:s'));
            $obj->set('card_number', $card_number);
            $obj->save();
            if ($i == 1)
                $first_id = $obj->getId();
        }
        return array($number_of_cards, $value, $first_id);
    }

    private function get_random_string($valid_chars, $length) {
        $random_string = "";
        $num_valid_chars = strlen($valid_chars);

        for ($i = 0; $i < $length; $i++) {
            $random_pick = mt_rand(1, $num_valid_chars);
            $random_char = $valid_chars[$random_pick - 1];
            $random_string .= $random_char;
        }

        return $random_string;
    }

}
